package com.foreveross.fetl.queue;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.inject.Inject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.foreveross.fetl.application.IFreightMonitorApplication;
import com.foreveross.fetl.application.IFreightMonitorCabinApplication;
import com.foreveross.fetl.application.ILogMessageApplication;
import com.foreveross.fetl.application.IPlaneInfoApplication;
import com.foreveross.fetl.common.Constant;
import com.foreveross.fetl.core.domain.freight.CabinEntity;
import com.foreveross.fetl.core.domain.freight.hbase.PlaneInfoEntity;
import com.foreveross.fetl.core.domain.freight.hbase.TransitchangeEntity;
import com.foreveross.fetl.util.DatabaseBeanUtils;
import com.foreveross.fetl.util.DateUtils;
import com.foreveross.fetl.util.RowkeyUtils;
import com.foreveross.fetl.util.StringUtils;
import com.foreveross.fetl.util.TestCommonData;
import com.foreveross.fetl.vo.LogMessageVO;

/**
 * 运价监控
 * LP_FREIGHT_MONITOR
 * @author LiuZhen
 */
@Component
public class FreightMonitorProcess {

	private static Logger log = Logger.getLogger("FreightMonitorProcess");

	@Inject private IFreightMonitorApplication freightMonitorApplication;
	@Inject private IPlaneInfoApplication planeInfoApplication;
	@Inject private IFreightMonitorCabinApplication freightMonitorCabinApplication;
	
	@Inject
	private ILogMessageApplication logMessageApplication;
	
	private int tasksNumber_type;//运价监控任务数 多少条rowkey
	private int failuresNumber_type;//运价监控失败数
	private int processNumber_type; //运价监控process 执行次数
	private int insertNumber_type; //运价监控插入条数 
	private long startTime_type;
	private Date executeStartTime_type;
	private LogMessageVO logMessage_type;
	private String taskTime_type=null;
	
	private int tasksNumber_caban;//仓位预警任务数 多少条rowkey
	private int failuresNumber_caban;//仓位预警失败数
	private int processNumber_caban; //仓位预警process 执行次数
	private int insertNumber_caban; //仓位预警插入条数 
	private long startTime_caban;
	private Date executeStartTime_caban;
	private LogMessageVO logMessage_caban;
	private String taskTime_caban=null;
	
	public void  typeRollBackNumber(){
		tasksNumber_type=0;
		failuresNumber_type=0;
		processNumber_type=0;
		insertNumber_type=0;
		startTime_type=System.currentTimeMillis();
		LogMessageVO startLogMessage =new LogMessageVO();
		startLogMessage.setExecuteClass("FreightMonitorProcess");
		startLogMessage.setExecuteName("运价监控");
		startLogMessage.setExecuteStartTime(new Date());
		startLogMessage.setExecuteType(1);
		logMessageApplication.create(startLogMessage);
		logMessage_type=startLogMessage;
	}
	
	public void cabanRollBackNumber(){
		tasksNumber_caban=0;
		failuresNumber_caban=0;
		processNumber_caban=0;
		insertNumber_caban=0;
		startTime_caban=System.currentTimeMillis();
		LogMessageVO startLogMessage =new LogMessageVO();
		startLogMessage.setExecuteClass("FreightMonitorProcess");
		startLogMessage.setExecuteName("舱位预警");
		startLogMessage.setExecuteStartTime(new Date());
		startLogMessage.setExecuteType(1);
		logMessageApplication.create(startLogMessage);
		logMessage_caban=startLogMessage;
	}
	
	
	public void execute() {
		typeRollBackNumber();
		cabanRollBackNumber();
		//update xiangsf 2013-09-28 将运价监控中与舱位变化预警两种分开来执行,并统计耗时
		log.info("start execute monitor cabin change....");
		long stime = System.currentTimeMillis();
//		this.process(currentGregorianCalendar.getTime(), new Date());
		Calendar c = Calendar.getInstance();
		c.add(Calendar.HOUR_OF_DAY, -1);
		try {
			log.info("start freightMonitor....");
			taskTime_type=DateUtils.format(c.getTime(), "yyyy-MM-dd HH");
			this.process(c.getTime(), new Date(),Constant.FREIGHT_MONITOR_TYPE);
			this.saveOrUpdateLog(logMessage_type, 2, Constant.FREIGHT_MONITOR_TYPE, null);
		} catch (Exception e) {
			e.printStackTrace();
			this.saveOrUpdateLog(logMessage_type, 3, Constant.FREIGHT_MONITOR_TYPE, StringUtils.getStackTrace(e));
			log.info("end freightMonitor.....,spend time"+(System.currentTimeMillis()-stime));
		}
		try {
			log.info("start cabin warning.....");
			taskTime_caban=DateUtils.format(c.getTime(), "yyyy-MM-dd HH");
			this.process(c.getTime(), new Date(),Constant.CABIN_WARNING_TYPE);	
			this.saveOrUpdateLog(logMessage_caban, 2, Constant.CABIN_WARNING_TYPE, null);
		} catch (Exception e) {
			this.saveOrUpdateLog(logMessage_caban, 3, Constant.CABIN_WARNING_TYPE, StringUtils.getStackTrace(e));
			e.printStackTrace();
		}finally{
			log.info("end cabin warning.....,spend time"+(System.currentTimeMillis()-stime));
			log.info("end execute monitor cabin change....spend time:"+(System.currentTimeMillis()-stime));
		}
	}
	
	public void manualTypeExecute(final String start,String time){
		this.typeRollBackNumber();
		try {
			List<String> timeList = Arrays.asList(time.split(";"));
			Calendar c = Calendar.getInstance();
			taskTime_type = start + " " +time;
			for (String s : timeList) {
				String str =start;
				str += s;
				Date startTime = DateUtils.parse(str, "yyyyMMddHH");
				c.setTime(startTime);
				c.add(Calendar.HOUR_OF_DAY, +1);
				Date endTime = c.getTime();
				this.process(startTime, endTime,Constant.FREIGHT_MONITOR_TYPE);
			}
			this.saveOrUpdateLog(logMessage_type, 2, Constant.FREIGHT_MONITOR_TYPE, null);
			} catch (Exception e) {
			this.saveOrUpdateLog(logMessage_type, 3, Constant.FREIGHT_MONITOR_TYPE, StringUtils.getStackTrace(e));
				log.error(StringUtils.getStackTrace(e));
			}
	}
	
	public void manualCabinExecute(final String start,String time){
		this.cabanRollBackNumber();
		try{
			List<String> timeList = Arrays.asList(time.split(";"));
			Calendar c = Calendar.getInstance();
			taskTime_caban=start + " " +time;
			for (String s : timeList) {
				String str =start;
				str += s;
				Date startTime = DateUtils.parse(str, "yyyyMMddHH");
				c.setTime(startTime);
				c.add(Calendar.HOUR_OF_DAY, +1);
				Date endTime = c.getTime();
				this.process(startTime, endTime, Constant.CABIN_WARNING_TYPE);
			}
			this.saveOrUpdateLog(logMessage_caban, 2, Constant.CABIN_WARNING_TYPE, null);
		}catch (Exception e) {
			this.saveOrUpdateLog(logMessage_type, 3, Constant.FREIGHT_MONITOR_TYPE, StringUtils.getStackTrace(e));
			log.error(StringUtils.getStackTrace(e));
		}
	}
	
	
	
	public void process(Date start, Date end,int type) throws Exception  {
		//大于今天的都要监控，所以>=syadate
		if(type == Constant.FREIGHT_MONITOR_TYPE)
			processMonitor(start, end, type);
		else if(type==Constant.CABIN_WARNING_TYPE)
			processCabinWarning(start, end, type);
	}
	private void processMonitor(Date start,Date end,int type) throws Exception{
		processNumber_type++;
		if(processNumber_type ==1){
			executeStartTime_type=new Date();
			}
		List<Map<String , Object>> data = DatabaseBeanUtils.getMapList("select * from fdc_flight_monitor where departdate >= sysdate() ", null);
		Map<String,String> flightNoMaps = new HashMap<String,String>();
		for (Map<String, Object> map : data) {
			String channel = (String) map.get("HBASEKEY");
			final String flightDate = map.get("DEPARTDATE").toString().replace("-", "");
			String flightNo = (String) map.get("FLIGHTNUMBER");
			final String tocity = (String) map.get("TOCODE");
			final String fromcity = (String) map.get("FROMCODE");
			final String area = (String) map.get("AREACODE");
			String[] channels = channel.split("/");
			String[] flightNos = flightNo.split("/");
			for (int i = 0; i < channels.length; i++) {
				final String tmpchannel = channels[i];
				final String tmpflightNo = flightNos[i];
				log.info("handle data....."+tmpchannel+tmpflightNo);
				//过滤掉重复的航班 
				//每次循环后把航班号存到一个map中，如果map中存在这个航班号 说明已经预处理过了，continue
				if(flightNoMaps.get(tmpflightNo)!=null){
					continue;
				}
				flightNoMaps.put(tmpflightNo, tmpflightNo);
				Calendar cStart = Calendar.getInstance();
				cStart.setTime(start);
				Calendar cEnd = Calendar.getInstance();
				cEnd.setTime(end);
				// 根据航班号查航班起飞时间,用来拼rowkey
				List<Map<String, Object>> flightinfos = null;
				flightinfos = DatabaseBeanUtils
						.getFlightInfo(tmpflightNo);
				if (flightinfos != null && flightinfos.size() > 0) {
					while (cStart.before(cEnd)) {
						String startStr = DateUtils.format(
								cStart.getTime(), "yyyyMMddHH");
						// 抓取日期(年月日时)_渠道_区域ID_起点(使用三字码)_终点(使用三字码)_起飞时间(年月日时)_航班ID
						for (Map<String, Object> flightinfo : flightinfos) {
							String hour = (String) flightinfo
									.get("FLIGHT_START_TIME");
							
							String startRowKey =RowkeyUtils.getRowKey(startStr, tmpchannel,  fromcity, tocity, flightDate+hour,tmpflightNo, RowkeyUtils.START_ROW_KEY);
							String endRowkey=RowkeyUtils.getRowKey(startStr, tmpchannel,  fromcity, tocity, flightDate+hour,tmpflightNo, RowkeyUtils.STOP_ROW_KEY);
						/*	StringBuffer startRowKey1 = new StringBuffer();
							startRowKey1.append(startStr)
									.append(tmpchannel).append(area)
									.append(fromcity).append(tocity)
									.append(flightDate).append(hour)
									.append(tmpflightNo);
							String tmpStr = startRowKey1.toString();
							for (int j = tmpStr.length(); j < RowkeyUtils.LENGTH; j++) {
								startRowKey1.append("0");
							}
							StringBuffer endRowKey1 = new StringBuffer();
							endRowKey1.append(tmpStr);
							for (int j = endRowKey1.length(); j < RowkeyUtils.LENGTH; j++) {
								endRowKey1.append("z");
							}
							log.info("type:"+type+"    startRowKey:" + startRowKey1
									+ "  endRowKey:  " + endRowKey1);*/
							processData(new StringBuffer(startRowKey), new StringBuffer(endRowkey),type);
						}
						cStart.add(Calendar.HOUR_OF_DAY, 1);// 开始时间加一小时
					}
				}
			}
		}
		flightNoMaps = null;data = null;
	
	}
	/**
	 * 仓位变动flg_deleted=0表示没有被删除的
	 * @param start
	 * @param end
	 * @throws Exception
	 */
	private void processCabinWarning(Date start, Date end,int type) throws Exception{
		processNumber_caban++;
		if(processNumber_caban ==1){
			executeStartTime_caban=new Date();
			}
		List<Map<String , Object>> data = DatabaseBeanUtils.getMapList("select * from fdc_alert_config where FLIGHTDATE >= sysdate() and flg_deleted=0 and ALERT_TYPE=1", null);
		for (Map<String, Object> map : data) {
			String channel = (String) map.get("CARRIER_KEY");
			String flightDate = map.get("FLIGHTDATE").toString().replace("-", "");
			String tocity = (String) map.get("TO_CITY");
			String fromcity = (String) map.get("FROM_CITY");
			String area = (String) map.get("AREA_CODE");
			String flightNo = (String) map.get("FLIGHTNO");
			Calendar cStart = Calendar.getInstance();
			cStart.setTime(start);
			Calendar cEnd = Calendar.getInstance();
			cEnd.setTime(end); //
			// 根据航班号查航班起飞时间,用来拼rowkey
			List<Map<String, Object>> flightinfos = null;
			// 抓回来的航班信息
			flightinfos = DatabaseBeanUtils.getFlightInfo(flightNo);
			if (flightinfos != null && flightinfos.size() > 0) {
				while (cStart.before(cEnd)) {
					String startStr = DateUtils.format(cStart.getTime(),"yyyyMMddHH"); //
					// 抓取日期(年月日时)_渠道_区域ID_起点(使用三字码)_终点(使用三字码)_起飞时间(年月日时)_航班ID
					for (Map<String, Object> flightinfo : flightinfos) {
						String hour = (String) flightinfo.get("FLIGHT_START_TIME");
						String startRowKey =RowkeyUtils.getRowKey(startStr, channel,  fromcity, tocity, flightDate+hour,flightNo, RowkeyUtils.START_ROW_KEY);
						String endRowkey=RowkeyUtils.getRowKey(startStr, channel, fromcity, tocity, flightDate+hour,flightNo, RowkeyUtils.STOP_ROW_KEY);
						/*StringBuffer startRowKey1 = new StringBuffer();
						startRowKey1.append(startStr).append(channel)
								.append(area).append(fromcity).append(tocity)
								.append(flightDate).append(hour)
								.append(flightNo);
						String tmpStr = startRowKey1.toString();
						for (int j = tmpStr.length(); j < RowkeyUtils.LENGTH; j++) {
							startRowKey1.append("0");
						}
						StringBuffer endRowKey1 = new StringBuffer();
						endRowKey1.append(tmpStr); // endRowKey1.append(sdf.format(c.getTime()));
						for (int j = endRowKey1.length(); j < RowkeyUtils.LENGTH; j++) {
							endRowKey1.append("z");
						}
						log.info("type:"+type+"   startRowKey:" + startRowKey1
								+ "  endRowKey:  " + endRowKey1);*/
						processData(new StringBuffer(startRowKey), new StringBuffer(endRowkey),type);
					}
					cStart.add(Calendar.HOUR_OF_DAY, 1);
				}
			}
		}
	}

	/**
	 * 处理运价监控和仓位预警逻辑
	 * @param startRowkey
	 * @param endRowkey
	 * @param type 1表示监控 2是仓位预警
	 */
	public void processData(StringBuffer startRowkey, StringBuffer endRowkey,int type) {
		/*
		 * 逻辑：
		 * 1、从planeinfo查数据出来，判断是那天第几次抓取，组装一个mysql的freightMonitor
		 * 2、存freightMonitor对象到mysql
		 * 2.1、存之前先查hbase 的Monitor表，查第几次HBaseTable.TABLE_FREIGHT_MONITOR
		 */
	//	System.out.println("====================="+startRowkey+"==="+endRowkey);
		List<PlaneInfoEntity> rs = planeInfoApplication.findByRowkey(startRowkey.toString(), endRowkey.toString());
		for (PlaneInfoEntity p : rs) {
			try {
				if(type==Constant.FREIGHT_MONITOR_TYPE){
					tasksNumber_type++;
				}else{
					tasksNumber_caban++;
				}
				/*
				 * 改点1、避免同一抓取时间同一航班同一航班日期数据出现两次
				 * 		2、增加创建时间
				 */
//				StringBuffer tmprowkey = new StringBuffer();
				//渠道 所在地 目的地 航班号 航班日期 抓取日期 抓取时分
				String grabChannelKey = TestCommonData.grabKeyMap.get(p.getGrabChannelId().toString());
//				tmprowkey.append(grabChannelKey)
//				.append(p.getFromCity())
//				.append(p.getToCity())
//				.append(StringUtils.leftPad(p.getFlightNo(), 8, '0'))
//				.append(p.getFlightDate().replace("-", "").substring(0, 8))
//				.append(p.getGrabDate().substring(0, 8));
//				String rowkey = tmprowkey.toString();
				Date mysql_flightdate = DateUtils.parse(p.getFlightDate(), Constant.flightDateFormat);
				Date mysql_grabdate = DateUtils.parse(p.getGrabDate().substring(0, 14), Constant.grabDateFormat);
				Object[] objs = new Object[]{type,grabChannelKey,
						p.getFromCity(),p.getToCity(),
						p.getFlightNo(),mysql_flightdate,
						mysql_grabdate};
				int grabNum = 1;
				int cabinNumForAdd = 0;
				int cabinNumForDel = 0;
				int cabinNumTotal = 0;
				//查询某航班某抓取时间是否已经抓取过数据
				List<com.foreveross.fetl.core.domain.freight.FreightMonitor> tmprs = 
						freightMonitorApplication.findByCondition(objs,"datetime");
				if(tmprs.size()>0){
					//数据已经存在，避免重复数据，预处理下一条数据
					log.info("the data is existed! process next data!");
					continue;
				}
				//查这个航班某天的所有数据
				tmprs = freightMonitorApplication.findByCondition(objs,"date");
				Set<com.foreveross.fetl.core.domain.freight.hbase.CabinEntity> cbh = p.getCabins();
				List<TransitchangeEntity> transits = p.getTransit();
				int[] tmparr = new int[3];
				//中转就不要统计仓位数了
				if(transits.size() > 0){
					tmparr[0] = 0;
					tmparr[1] = 0;
					tmparr[2] = 1;
				}else {
					if(tmprs.size() > 0){
						//第抓取次数
						grabNum = tmprs.size()+1;
						//统计仓位
						 // 1、取到最近一次的航班数据   tmprs有order 所以取第一个
						//2、取出当天最近一次抓取航班的仓位数据
						List<CabinEntity> cbs = freightMonitorCabinApplication.findByMonitorId(tmprs.get(0).getId());
						//3、p.getCabins()和上一次的仓位数据比较，组装出仓位变化数
						this.compareCabinNum(cbh, cbs, cabinNumForAdd,cabinNumForDel,cabinNumTotal,grabChannelKey,tmparr);
					}else {
						log.info("the grabnum is 1,to acquire data yesterday");
						//如果今天是第一次，则找昨天最后一次的数据
						Date yesterday = DateUtils.getSpecifiedDayBefore(mysql_grabdate);
						//查询昨天抓取的数据
						objs[objs.length-1] = yesterday;
						tmprs = freightMonitorApplication.findByCondition(objs,"date");
						//统计仓位
						 // 1、取到最近一次的航班数据   tmprs有order 所以取第一个
						//2、取出当天最近一次抓取航班的仓位数据
						List<CabinEntity> cbs = null;
						if(tmprs.size() == 0){
							//如果昨天还是没有数据
							cbs = new ArrayList<CabinEntity>();
						}else{
							cbs = freightMonitorCabinApplication.findByMonitorId(tmprs.get(0).getId());
						}
						//3、p.getCabins()和上一次的仓位数据比较，组装出仓位变化数
						this.compareCabinNum(cbh, cbs, cabinNumForAdd,cabinNumForDel,cabinNumTotal,grabChannelKey,tmparr);
					}
				}
				// 仓位个数 ==cabinNumTotal
				cabinNumForAdd = tmparr[0];
				cabinNumForDel = tmparr[1];
				cabinNumTotal = tmparr[2];
				String tmpId = UUID.randomUUID().toString();
				com.foreveross.fetl.core.domain.freight.FreightMonitor f_mysql = new com.foreveross.fetl.core.domain.freight.FreightMonitor(
						tmpId, p.getFlightNo(), mysql_flightdate,
						mysql_grabdate,type, grabNum, cabinNumTotal, cabinNumForAdd,
						cabinNumForDel, p.getLowerPrice(), p.getHighPrice(),
						p.getGrabChannel(), grabChannelKey, p.getFromCity(),
						p.getToCity(), p.getToCityName(), p.getFromCityName());
//				FreightMonitor f_hbase = new 
//						FreightMonitor(
//								p.getFlightNo(), p.getFlightDate(), p.getGrabDate(),
//								grabNum, cabinNumTotal, cabinNumForAdd, cabinNumForDel,
//								p.getLowerPrice(), p.getHighPrice(), p.getGrabChannel(),grabChannelKey,
//								p.getFromCity(), p.getToCity(), p.getFromCityName(),
//								p.getToCityName(), p.getCabins());
				log.info("flightno:"+p.getFlightNo()+"  flightdate: "+p.getFlightDate() + "  grabdate: "+p.getGrabDate());
//				freightMonitorHbaseApplication.create(f_hbase);
				freightMonitorApplication.create(f_mysql);
				if(type==Constant.FREIGHT_MONITOR_TYPE){
					insertNumber_type++;
				}else{
					insertNumber_caban++;
				}
				//组装仓位数据
				Set<com.foreveross.fetl.core.domain.freight.hbase.CabinEntity> setCabType =new HashSet<com.foreveross.fetl.core.domain.freight.hbase.CabinEntity>();
				for (com.foreveross.fetl.core.domain.freight.hbase.CabinEntity cb : cbh) {
					if(grabChannelKey.equals(Constant.GUOHANG_KEY)){
						setCabType.add(cb);
					}else{
						CabinEntity c = new CabinEntity(cb.getSubCabinName(),
								cb.getPrice(), cb.getProductName(), 2,
								null, tmpId);
						freightMonitorCabinApplication.create(c);
						if(cb.getCabinType()!=null){
							if(setCabType==null || setCabType.isEmpty()){
								setCabType.add(cb);
							}else{
								boolean isExit =false;
								for(com.foreveross.fetl.core.domain.freight.hbase.CabinEntity cabin : setCabType){
									if(cb.getCabinType().equals(cabin.getCabinType())){
										isExit=true;
										if(cabin.getPrice()>=cb.getPrice()){
											cabin=cb;
										}
									}
								}
								if(!isExit){
									setCabType.add(cb);
								}
							}
						}
					}
					
				}
				for(com.foreveross.fetl.core.domain.freight.hbase.CabinEntity cabin:setCabType){
					CabinEntity c1 = new CabinEntity(null,
							cabin.getPrice(), cabin.getProductName(), 1,
							cabin.getCabinType(), tmpId);
					freightMonitorCabinApplication.create(c1);
				}
				
				f_mysql = null;cbh=null;transits=null;
			} catch (Exception e) {
				if(type==Constant.FREIGHT_MONITOR_TYPE){
					failuresNumber_type++;
				}else{
					failuresNumber_caban++;
				}
				e.printStackTrace();
			}
		}
		rs = null;
	}
	/**
	 * 比较仓位变化数
	 * @param cbh	预处理的仓位
	 * @param cbs	今天最近一次的仓位
	 * @param cabinNumForAdd	本次和上次比较后的新增仓位数
	 * @param cabinNumForDel	本次和上次比较后的减少仓位数
	 * @return
	 */
	private void compareCabinNum(Set<com.foreveross.fetl.core.domain.freight.hbase.CabinEntity> cbh,
			List<CabinEntity> cbs,int cabinNumForAdd,
			int cabinNumForDel,int cabinNumTotal,
			String grabChannelKey,int[] tmparr){
		Map<String,Double> map_hbase = new HashMap<String,Double>();
		//把这次仓位都放在一个map里
		this.cabinEntityHbase2Map(cbh,map_hbase, grabChannelKey);
		Map<String,Double> map_mysql = new HashMap<String,Double>();
		//把上次仓位都放在一个map里
		this.cabinEntityMysql2Map(cbs, map_mysql, grabChannelKey);
		//仓位数
		cabinNumTotal = map_hbase.size();
		//比较新增了多少仓位和减少了多少仓位
		Set<String> map_hbase_keys = map_hbase.keySet();
		for (String map_hbase_key : map_hbase_keys) {
			//如果上次仓位中不包含 （这次仓位中的）当前循环仓位 说明当前循环仓位是这次新增的 add++
			if(!map_mysql.containsKey(map_hbase_key))
				cabinNumForAdd ++;
		}
		map_hbase_keys = null;
		Set<String> map_mysql_keys = map_mysql.keySet();
		for (String map_mysql_key : map_mysql_keys) {
			//如果这次仓位中不包含 (上次仓位中)当前循环中的仓位 说明这次仓位删除了(上次仓位中)当前这个仓位
			if(!map_hbase.containsKey(map_mysql_key))
				cabinNumForDel ++;
		}
		map_mysql_keys = null;map_hbase=null;map_mysql=null;cbs=null;
		tmparr[0] = cabinNumForAdd;
		tmparr[1] = cabinNumForDel;
		tmparr[2] = cabinNumTotal;
	}
	/**
	 * 转换这次要统计的仓位信息（国航统计lv1，海航是网站专享）
	 * @param cbh
	 * @param map_hbase
	 * @param grabChannelkey
	 */
	private void cabinEntityHbase2Map(Set<com.foreveross.fetl.core.domain.freight.hbase.CabinEntity> cbh,Map<String,Double> map_hbase,String grabChannelkey){
		//国航没有二级仓位 才put lever 1 其他航空公司不要计算lever为1的
		if(grabChannelkey.equals(Constant.GUOHANG_KEY)){
			for (com.foreveross.fetl.core.domain.freight.hbase.CabinEntity tmp : cbh) {
				map_hbase.put(tmp.getProductName(), tmp.getPrice());
			}
		}else if(grabChannelkey.equals(Constant.HAIHANG_KEY)){
			//海航的话 只取网上专享
			for (com.foreveross.fetl.core.domain.freight.hbase.CabinEntity tmp : cbh) {
					if(tmp.getProductName().equals(Constant.WEB_EXCLUSIVE))
						map_hbase.put(null!=tmp.getProductName()?
							tmp.getProductName()+tmp.getSubCabinName():
								tmp.getSubCabinName(), tmp.getPrice());
			}
		}else{
			for (com.foreveross.fetl.core.domain.freight.hbase.CabinEntity tmp : cbh) {
				map_hbase.put(tmp.getSubCabinName(), tmp.getPrice());
			}
		}
	}
	/**
	 * 转换上次的仓位信息
	 * @param cbs
	 * @param map_hbase
	 * @param grabChannelkey
	 */
	private void cabinEntityMysql2Map(List<CabinEntity> cbs,Map<String,Double> map_mysql,String grabChannelkey){
		if(grabChannelkey.equals(Constant.GUOHANG_KEY)){
			for (CabinEntity tmp : cbs) {
					map_mysql.put(tmp.getProductName(), tmp.getPrice());
			}
		}else if(grabChannelkey.equals(Constant.HAIHANG_KEY)){
			//海航的话 只取网上专享
			for (CabinEntity tmp : cbs) {
				if(tmp.getLevel() == 2){
					if(tmp.getProductName().equals(Constant.WEB_EXCLUSIVE))
						map_mysql.put(null!=tmp.getProductName()?
							tmp.getProductName()+tmp.getCabinName():
								tmp.getCabinName(), tmp.getPrice());
				}
			}
		}else{
			for (CabinEntity tmp : cbs) {
				if(tmp.getLevel() == 2)
					map_mysql.put(tmp.getCabinName(), tmp.getPrice());
			}
		}
	}
	
	private void saveOrUpdateLog(LogMessageVO vo,int executeType,int type,String result){
		LogMessageVO logMes =new LogMessageVO();
		if(null!=vo){
			logMes=logMessageApplication.getOneLogMessage(vo.getExecuteClass(), vo.getExecuteName(), vo.getExecuteStartTime(), vo.getExecuteType());
		}
		logMes.setExecuteClass("FreightMonitorProcess");
		logMes.setExecuteType(executeType);
		if(result!=null){
			if(result.length()>200){
				result=result.substring(0, 199);
			}
			logMes.setResult(result);
		}
			if(type==Constant.FREIGHT_MONITOR_TYPE){
				logMes.setExecuteName("运价监控");
				logMes.setExecuteStartTime(executeStartTime_type);
				logMes.setExecuteEndTime(new Date());
				logMes.setFailuresNumber(failuresNumber_type);
				logMes.setTasksNumber(tasksNumber_type);
				logMes.setInsertNumber(insertNumber_type);
				logMes.setExecuteTotalTime(System.currentTimeMillis()-startTime_type);
				logMes.setTaskTime(taskTime_type);
			}
			if(type==Constant.CABIN_WARNING_TYPE){
				logMes.setExecuteName("舱位预警");
				logMes.setExecuteStartTime(executeStartTime_caban);
				logMes.setExecuteEndTime(new Date());
				logMes.setFailuresNumber(failuresNumber_caban);
				logMes.setTasksNumber(tasksNumber_caban);
				logMes.setInsertNumber(insertNumber_caban);
				logMes.setExecuteTotalTime(System.currentTimeMillis()-startTime_caban);
				logMes.setTaskTime(taskTime_caban);
			}
			if(logMes.getId()!=null && logMes.getId()!=0){
				logMessageApplication.update(logMes);
			}else{
				logMessageApplication.create(logMes);
			}
		
		
	}
//	public static void main(String[] args) {
//		ConfigContainer.getInstance().register(DefaultPropertiesLoader.class);
//		
//		ConfigContainer.getInstance().register(HBasePropertiesLoader.class);
//		ApplicationContext ctx = new ClassPathXmlApplicationContext("META-INF/spring/root.xml"); 
//		FreightMonitorProcess fp = (FreightMonitorProcess) ctx.getBean("freightMonitorProcess");
//		System.out.println(fp.planeInfoApplication);
////		planeInfoApplication = (IPlaneInfoApplication) ctx.getBean("planeInfoApplication");
////		freightMonitorHbaseApplication = (IFreightMonitorApplication) ctx.getBean("freightMonitorHbaseApplication");
////		freightMonitorApplication = (IFreightMonitorApplication) ctx.getBean("freightMonitorApplication");
////		freightMonitorCabinApplication = (IFreightMonitorCabinApplication)ctx.getBean("freightMonitorCabinApplication");
//		
//		FreightMonitorProcess job = new FreightMonitorProcess();
//		//抓取日期(年月日)_渠道_区域ID_起点(使用三字码)_终点(使用三字码)_起飞时间(年月日)_航班号
////		Date start = DateUtils.parse("2013082210", "yyyyMMddHH");
////		Date end = DateUtils.parse("2013082311", "yyyyMMddHH");
//		final Calendar c = Calendar.getInstance();
//		c.add(Calendar.HOUR_OF_DAY, -2);
//		Calendar c2 = Calendar.getInstance();
//		c2.add(Calendar.HOUR_OF_DAY, -0);
////		process(c.getTime(), new Date());
//		try {
////			job.process(start, end);
//			job.process(c.getTime(), c2.getTime());
////			job.processData(new StringBuffer(), new StringBuffer());
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
////		String test = "2013-08-02";
////		System.out.println(test.replace("-", ""));
////		Map map = new HashMap();
////		System.out.println(map.containsKey("a"));
////		final Calendar c = Calendar.getInstance();
////		c.add(Calendar.HOUR_OF_DAY, -48);
////		Calendar c2 = Calendar.getInstance();
////		c2.add(Calendar.HOUR_OF_DAY, -42);
////		System.out.println(c.getTime());
////		System.out.println(c2.getTime());
//		String s = "20000/20006/20005";
//		String[] ss = s.split("/");
//		
//		for (int i = 0; i < ss.length; i++) {
//			System.out.println(ss[i]);
//		}
//		new FreightMonitorProcess().execute();
//	}
}
